<template>
  <div class="order-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索订单号"
        prefix-icon="el-icon-search"
        clearable
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
        class="search-input">
      </el-input>
      <el-select v-model="orderStatus" placeholder="订单状态" clearable @change="handleSearch">
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </div>

    <!-- 订单列表 -->
    <el-table
      v-loading="loading"
      :data="orders"
      border
      style="width: 100%">
      <el-table-column
        prop="orderNo"
        label="订单号"
        width="180">
      </el-table-column>
      <el-table-column label="商品信息" min-width="400">
        <template slot-scope="scope">
          <div class="order-items">
            <div v-if="!scope.row.orderItems || scope.row.orderItems.length === 0" class="no-items">
              暂无商品信息
            </div>
            <div v-for="(item, index) in scope.row.orderItems" :key="index" class="order-item">
              <el-image
                :src="getProductImage(item)"
                :preview-src-list="[getProductImage(item)]"
                class="product-image">
              </el-image>
              <div class="item-info">
                <div class="item-name">{{ getProductName(item, index) }}</div>
                <div class="item-price">¥{{ item.price || 0 }} × {{ item.quantity || 0 }}</div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="totalAmount"
        label="总金额"
        width="120">
        <template slot-scope="scope">
          ¥{{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="下单时间"
        width="180">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createdTime || scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleDetail(scope.row)">
            详情
          </el-button>
          <el-button
            v-if="isPending(scope.row.status)"
            size="mini"
            type="success"
            @click="handlePay(scope.row)">
            付款
          </el-button>
          <el-button
            v-if="isPending(scope.row.status)"
            size="mini"
            type="danger"
            @click="handleCancel(scope.row)">
            取消
          </el-button>
          <el-button
            v-if="isShipped(scope.row.status)"
            size="mini"
            type="success"
            @click="handleConfirmReceive(scope.row)">
            确认收货
          </el-button>
          <el-button
            v-if="isCompletedOrCancelled(scope.row.status)"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { payOrder, confirmReceive } from '@/api/order'

export default {
  name: 'OrderList',
  data() {
    return {
      loading: false,
      searchQuery: '',
      orderStatus: '',
      currentPage: 1,
      pageSize: 10,
      statusOptions: [
        { value: 'pending', label: '待付款' },
        { value: 'paid', label: '已付款' },
        { value: 'shipped', label: '已发货' },
        { value: 'completed', label: '已完成' },
        { value: 'cancelled', label: '已取消' }
      ]
    }
  },
  computed: {
    ...mapState('order', ['orders', 'total'])
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    ...mapActions('order', ['getMyOrderList', 'cancelOrder', 'deleteOrder']),

    async fetchOrders() {
      try {
        this.loading = true
        await this.getMyOrderList({
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery,
          status: this.orderStatus
        })
      } catch (error) {
        this.$message.error('获取订单列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.currentPage = 1
      this.fetchOrders()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchOrders()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchOrders()
    },

    getStatusType(status) {
      // 处理数字状态码和字符串状态
      const statusVal = typeof status === 'number' ? String(status) : status?.toLowerCase();
      
      const statusMap = {
        'pending': 'warning',
        'paid': 'primary',
        'shipped': 'info',
        'completed': 'success',
        'cancelled': 'danger',
        // 数字状态码映射
        '0': 'warning',  // 待付款
        '1': 'primary',  // 已付款
        '2': 'info',     // 已发货
        '3': 'success',  // 已完成
        '4': 'danger'    // 已取消
      }
      return statusMap[statusVal] || 'info'
    },

    getStatusLabel(status) {
      // 处理数字状态码和字符串状态
      const statusVal = typeof status === 'number' ? String(status) : status?.toLowerCase();
      
      const statusLabels = {
        'pending': '待付款',
        'paid': '已付款',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消',
        // 数字状态码映射
        '0': '待付款',
        '1': '已付款',
        '2': '已发货',
        '3': '已完成',
        '4': '已取消'
      }
      
      return statusLabels[statusVal] || '未知状态(' + status + ')'
    },

    handleDetail(order) {
      this.$router.push(`/main/shop/orders/${order.id}`)
    },

    async handlePay(order) {
      try {
        await payOrder(order.id)
        this.$message.success('支付成功')
        this.fetchOrders()
      } catch (error) {
        this.$message.error('支付失败')
      }
    },

    async handleCancel(order) {
      try {
        await this.$confirm('确认取消该订单吗？', '提示', {
          type: 'warning'
        })
        await this.cancelOrder(order.id)
        this.$message.success('订单已取消')
        this.fetchOrders()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('取消订单失败')
        }
      }
    },

    async handleConfirmReceive(order) {
      try {
        await this.$confirm('确认已收到商品吗？', '提示', {
          type: 'warning'
        })
        await confirmReceive(order.id)
        this.$message.success('确认收货成功')
        this.fetchOrders()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('确认收货失败')
        }
      }
    },

    async handleDelete(order) {
      try {
        await this.$confirm('确认删除该订单吗？删除后不可恢复', '提示', {
          type: 'warning'
        })
        await this.deleteOrder(order.id)
        this.$message.success('删除成功')
        this.fetchOrders()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },

    // 辅助方法判断订单状态
    isPending(status) {
      if (typeof status === 'string') {
        return status.toUpperCase() === 'PENDING' || status.toLowerCase() === 'pending';
      }
      return status === 0;
    },
    
    isShipped(status) {
      if (typeof status === 'string') {
        return status.toUpperCase() === 'SHIPPED' || status.toLowerCase() === 'shipped';
      }
      return status === 2;
    },
    
    isCompletedOrCancelled(status) {
      if (typeof status === 'string') {
        const upperStatus = status.toUpperCase();
        return upperStatus === 'COMPLETED' || upperStatus === 'CANCELLED' || 
               status.toLowerCase() === 'completed' || status.toLowerCase() === 'cancelled';
      }
      return status === 3 || status === 4;
    },

    getProductImage(item) {
      // 获取商品图片URL
      let imageUrl = item.imageUrl || item.productImage || null;
      
      if (!imageUrl) {
        return require('@/assets/default.jpg');
      }
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
        return imageUrl;
      }
      
      // 确保路径以 / 开头
      if (!imageUrl.startsWith('/')) {
        imageUrl = '/' + imageUrl;
      }
      
      // 构建完整URL
      return serverUrl + imageUrl;
    },

    getProductName(item, index) {
      return item.name || item.productName || `商品${index + 1}`
    },

    formatDateTime(timestamp) {
      if (!timestamp) return '暂无数据';
      
      let date;
      try {
        // 尝试将字符串转换为Date对象
        if (typeof timestamp === 'string') {
          // 处理后端返回的标准格式 (2023-03-30T19:32:58)
          if (timestamp.includes('T')) {
            date = new Date(timestamp);
          } else {
            // 处理可能的其他格式 (2023-03-30 19:32:58)
            date = new Date(timestamp.replace(/-/g, '/'));
          }
        } else if (timestamp instanceof Date) {
          date = timestamp;
        } else {
          // 假设是时间戳（毫秒）
          date = new Date(Number(timestamp));
        }
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return timestamp; // 如果转换失败，返回原始字符串
        }
        
        // 格式化为 YYYY-MM-DD HH:mm:ss
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return timestamp; // 返回原始值
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.order-list {
  padding: 20px;

  .search-bar {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;

    .search-input {
      width: 300px;
    }
  }

  .order-items {
    .order-item {
      display: flex;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .product-image {
        width: 60px;
        height: 60px;
        margin-right: 10px;
      }

      .item-info {
        flex: 1;

        .item-name {
          margin-bottom: 5px;
          color: #303133;
        }

        .item-price {
          color: #909399;
          font-size: 13px;
        }
      }
    }
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 